# -*- coding: utf-8 -*-
import numpy as np
from math import sqrt

def accuracy_score( y_true, y_predict ):
    # knn 算法的精确度
    return np.sum( y_predict == y_true )/len( y_true )

def mean_squared_error( y_true, y_predict ):
    # 计算y_true和y_predict之间的MSE
    return ( np.sum( ( y_true - y_predict ) ** 2 ) ) / len( y_true )

def root_mean_squared_error( y_true, y_predict ):
    # 计算y_true和y_predict之间的RMSE
    return sqrt( mean_squared_error( y_true, y_predict ) )

def mean_absolute_error( y_true, y_predict ):
    # 计算y_true和y_predict之间的MAE
    return np.sum( np.absolute( y_true - y_predict ) ) / len( y_true )

def r2_score( y_true, y_predict ):
    # 计算 y_ture, y_predict 之间的 R Square
    return 1 - ( mean_squared_error( y_true, y_predict ) / np.var( y_true ) )
# TF
def TN( y_true, y_predict ):
    return np.sum( ( y_true == 0 ) & ( y_predict == 0 ) )

# FP
def FP( y_true, y_predict ):
    return np.sum( ( y_true == 0 ) & ( y_predict == 1 ) )

# FN
def FN( y_true, y_predict ):
    return np.sum( ( y_true == 1 ) & ( y_predict == 0 ) )

# TP
def TP( y_true, y_predict ):
    return np.sum( ( y_true == 1 ) & ( y_predict == 1 ) )

# 混淆矩阵
def comfusion_matrix( y_true, y_predict ):
    return np.array([
                [TN( y_true, y_predict ),FP( y_true, y_predict )],
                [FN( y_true, y_predict ),TP( y_true, y_predict )]
            ])
# TPR
def TPR( y_true, y_predict ):
    tp = TP( y_true, y_predict )
    fn = FN( y_true, y_predict )
    try:
        return tp / ( tp + fn )
    except:
        return 0.
    
# FPR
def FPR( y_true, y_predict ):
    fp = FP( y_true, y_predict )
    tn = TN( y_true, y_predict )
    try:
        return fp / ( fp + tn )
    except:
        return 0.
    